#include <my_head.h>
typedef struct{
  const char *src_file;
    const char *dest_file;
    int offset;
    int cp_len;
} fuzhi;

int get_srcfile_len_and_create_destfile(const char *src_file, const char *dest_file){
    int fd = 0;
    if(-1 == (fd = open(src_file, O_RDONLY))){
        ERR_LOG("open error");
    }
    int length = lseek(fd, 0, SEEK_END);
    close(fd);
    if(-1 == (fd = open(dest_file, O_WRONLY|O_CREAT|O_TRUNC, 0666))){
        ERR_LOG("open error");
    }
    close(fd);
    return length;
}
void copy_file(void*xian){
    fuzhi *p=(fuzhi *)xian;
    int fd_src = open(p->src_file, O_RDONLY);
    if(-1 == fd_src)
        ERR_LOG("open error");
    int fd_dest = open(p->dest_file, O_WRONLY);
    if(-1 == fd_dest)
        ERR_LOG("open error");
    lseek(fd_src, p->offset, SEEK_SET);
    lseek(fd_dest, p->offset, SEEK_SET);
    char buff[10];
    int count = 0; 
    int nbytes = 0;
    while(0 < (nbytes = read(fd_src, buff, sizeof(buff)))){
        count += nbytes;
        if(count >= p->cp_len){
            write(fd_dest, buff, p->cp_len-(count-nbytes));
            break;
        }
        write(fd_dest, buff, nbytes);
    }
    close(fd_src);
    close(fd_dest);
}
 int main(int argc, char const *argv[])
 {
    if(3 != argc){
        printf("Usage : %s src_file dest_file\n", argv[0]);
        return -1;
    }
    int ret=0;
    int ret2=0;
    pthread_t tid1 = 0;
    pthread_t tid2 = 0;
    int length = get_srcfile_len_and_create_destfile(argv[1], argv[2]);
    fuzhi xian1 = {argv[1], argv[2], 0, length/2};
    fuzhi xian2 = {argv[1], argv[2], length/2, length - length/2};
    if(0 != (ret = pthread_create(&tid1, NULL, copy_file, &xian1))){
        printf("pthread_create error : [%d] [%s]\n", ret, strerror(ret));
        exit(-1);
    }
    if(0 != (ret2 = pthread_create(&tid2, NULL, copy_file, &xian2))){
        printf("pthread_create error : [%d] [%s]\n", ret2, strerror(ret2));
        exit(-1);
    }
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    return 0;
 }
 